function getContainer() {
  const modals = document.getElementsByClassName('ant-modal-root')
  return modals[modals.length - 1]
}

function getStyle(dom, attr) {
  if (window.document.style) {
    return dom.style[attr]
  } else {
    return getComputedStyle(dom, false)[attr]
  }
}

function initEvent() {
  setTimeout(() => {
    const container = getContainer()
    const header = container.getElementsByClassName('ant-modal-header')[0]
    header.style.cursor = 'all-s `croll'
    const modal = container.getElementsByClassName('ant-modal')[0]
    header.onmousedown = e => {
      document.body.onselectstart = () => false
      const disX = e.clientX
      const disY = e.clientY
      const screenWidth = document.body.clientWidth
      const screenHeight = document.documentElement.clientHeight

      const dragDomWidth = modal.offsetWidth
      const dragDomheight = modal.offsetHeight

      const minDragDomLeft = modal.offsetLeft

      const maxDragDomLeft = screenWidth - modal.offsetLeft - dragDomWidth
      const minDragDomTop = modal.offsetTop
      const maxDragDomTop = screenHeight - modal.offsetTop - dragDomheight
      // 获取到的值带px 正则匹配替换
      const domLeft = getStyle(modal, 'left')
      const domTop = getStyle(modal, 'top')
      let styL = domLeft
      let styT = domTop
      if (domLeft.includes('%')) {
        styL =
          +document.body.clientWidth * (+domLeft.replace(/%/g, '') / 100)
        styT =
          +document.body.clientHeight * (+domTop.replace(/%/g, '') / 100)
      } else {
        styL = +domLeft.replace(/px/g, '')
        styT = +domTop.replace(/px/g, '')
      }

      document.onmousemove = event => {
        let left = event.clientX - disX
        let top = event.clientY - disY

        if (-left > minDragDomLeft) {
          left = -minDragDomLeft
        } else if (left > maxDragDomLeft) {
          left = maxDragDomLeft
        }

        if (-top > minDragDomTop) {
          top = -minDragDomTop
        } else if (top > maxDragDomTop) {
          top = maxDragDomTop
        }
        modal.style.cssText += `;left:${left + styL}px;top:${top + styT}px;`
      }
      document.onmouseup = () => {
        document.onmousemove = null
        document.onmouseup = null
      }
    }
  }, 0)
}

function destroyEvent() {
  const container = getContainer()
  if (container) {
    const header = container.getElementsByClassName('ant-modal-header')[0]
    try {
      header.onmousedown = null
    } catch (e) {
      console.log(e)
    }
  }
}

export function register(register) {
  if (register) {
    initEvent()
  } else {
    destroyEvent()
  }
}
